var paginationMaxLength=8;//分页栏的最大显示条数
var onlyOnePageIsShow = true;//只有一页的时候是否显示
function paginationInit(where){
    $('[am-pagination = pagination_'+where+']').each(function(){
        initPagination($(this), where);
    });
}
function addPageNum(pageNumber, where){
    $('#prePage'+where).attr("totalpage", pageNumber);
}
function initPagination(element, where){
    element.html('');
    var pagenumber = element.attr('pagenumber');
    var totalpage = element.attr('totalpage');
    var pMaxLength = element.attr('paginationMaxLength');
    var onePageIsShow = element.attr('onlyOnePageIsShow');
    // console.log(totalpage)
    if(isNeedPagination(Number(totalpage),onePageIsShow)){
        var content = '<ul class="am-pagination am-pagination-centered"><li value="0"><a href="javascript:void(0);">«</a></li>';
        for(var i =1; i<=totalpage;i++){
            content +='<li value="'+i+'"><a href="javascript:void(0);">'+i+'</a></li>'
        }
        content +='<li value="-1"><a href="javascript:void(0);">»</a></li></ul>';
        element.append(content);
        element.children('ul').children('li[value='+pagenumber+']').attr('class','am-active');
        setDisplayMaxLength(element,pMaxLength);
        addClickListener(element, where);
    }
}

function setDisplayMaxLength(element,len){
    var currentpage =  Number(element.attr('pagenumber'));
    var totoalpage = Number(element.attr('totalpage'));
    if(checkParamIsPositiveInteger(len)){
        len = Number(len);
    }else{
        len =paginationMaxLength;
    }
    if(len<totoalpage){
        var temp1 = parseInt((len-1)/2);
        var temp2 = parseInt(len/2);
        if(temp1<temp2){
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1 + 1;
        }else{
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1;
        }
        if(leftstart<1){
            rightend +=(1-leftstart);
            leftstart = 1;
        }
        if(rightend>totoalpage){
            if(leftstart>1){
                leftstart -=(rightend-totoalpage);
            }
            rightend =totoalpage;
        }
        if(leftstart<1){
            leftstart=1
        }
        while(leftstart >1){
            element.children('ul').children('li[value = '+(--leftstart)+']').css('display','none');
        }
        while(rightend <totoalpage){
            element.children('ul').children('li[value = '+(++rightend)+']').css('display','none');
        }
    }
}

function isNeedPagination(totalpage,settingfromHTML){
    var condition ;
    if(settingfromHTML == "true"){
        condition = true;
    }else if(settingfromHTML == 'false'){
        condition = false;
    }else {
        condition = onlyOnePageIsShow;
    }
    if(condition && totalpage<1){
        return false;
    }else if(!condition && totalpage<=1){
        return false;
    }
    return true;
}
//根据页面pagenumber、my_totoalpage更新分页，参数element传的是分页的容器

function addClickListener(element, where){
    element.children('ul').children('li').bind('click',function(){
        var temp = Number($(this).attr('value'));
        var pagenumber = Number($(this).parent().parent().attr('pagenumber'));
        var totalpage = Number($(this).parent().parent().attr('totalpage'));
        if(temp == 0){
            temp = pagenumber-1;
        }else if(temp == -1){
            temp = pagenumber+1;
        }
        if(temp != pagenumber && temp !=0 && temp<=totalpage){
            $(this).parent().parent().attr('pagenumber',temp);
            paginationClick(element.attr("id"), where);
            initPagination(element, where);
        }
        return false;
    })
}
function checkParamIsPositiveInteger(param){
    var reg = /^[1-9]+[0-9]*]*$/;
    return reg.test(param);
}

//用户需要自己实现的点击事件，参数为分页容器的id
function paginationClick(pagination_id, where){
    var pagenumber = $('#'+pagination_id+'').attr('pagenumber');
    JSON.stringify(pagenumber);
    if(where == 1){
        if($("#logIsSearch").val() == 1){
            $.ajax({
                type:"POST",
                url:constUrl+"log/search",
                dataType:"json",
                data: {
                    startDate: $("#logStartDateTemp").val(),
                    endDate: $("#logEndDateTemp").val(),
                    content: $("#logSearchContentTemp").val(),
                    onePageCount: "10",
                    currentPage: pagenumber,
                    operateLog:1
                },
                success:function(data){
                    addBox(data.result.logs, 'logTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        } else {
            $.ajax({
                type:"POST",
                url:constUrl+"log/list",
                dataType:"json",
                data: {
                    onePageCount: "10",
                    currentPage: pagenumber
                },
                success:function(data){
                    addBox(data.result.logs, 'logTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        }
    }
    if(where == 2){
        if($("#runIsSearch").val() == 1){
            $.ajax({
                type:"POST",
                url:constUrl+"log/search",
                dataType:"json",
                data: {
                    startDate: $("#runStartDateTemp").val(),
                    endDate: $("#runEndDateTemp").val(),
                    content: $("#runSearchContentTemp").val(),
                    onePageCount: "10",
                    currentPage: pagenumber,
                    operateLog: 0
                },
                success:function(data){
                    addBox(data.result.logs, 'runTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        } else {
            $.ajax({
                type: "POST",
                url: constUrl+"socketlog/list",
                dataType: "json",
                data: {
                    onePageCount: "10",
                    currentPage: pagenumber
                },
                success: function (data) {
                    addBox(data.result.logs, 'runTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        }
    }
}

function addBox(data, where){
    console.log(where)
    $("tr").remove("."+where+"Tr");
    setTimeout(function (){addTr(data, where);},100);
}

function addTr(data, where){
    if(where == "logTableList"){
        for(var i=0;i<data.length;i++) {
            $("#"+where).append(
                "<tr class='"+where+"Tr'>" +
                "<td>"+(i+1)+"</td>"+
                "<td>"+data[i].logLevel+"</td>"+
                "<td>"+data[i].operateTarget+"</td>"+
                "<td>"+data[i].operateType+"</td>"+
                "<td>"+data[i].result+"</td>"+
                "<td>"+data[i].time+"</td>"+
                "<td>"+data[i].userName+"</td>"+
                "</tr>"
            );
        }
    }
    if(where == "runTableList"){
        for(var i=0;i<data.length;i++) {
            $("#"+where).append(
                "<tr class='"+where+"Tr'>" +
                "<td>"+(i+1)+"</td>"+
                "<td>"+data[i].algorithmSchedule+"</td>"+
                "<td>"+data[i].algorithmState+"</td>"+
                "<td>"+data[i].logFileUri+"</td>"+
                "<td>"+data[i].logLevel+"</td>"+
                // "<td>"+data[i].logMessage+"</td>"+
                "<td>"+data[i].subTaskHash+"</td>"+
                "<td>"+data[i].taskHash+"</td>"+
                "<td>"+data[i].time+"</td>"+
                "<td><div class='am-btn-toolbar'>"+
                "<div class='am-btn-group am-btn-group-xs'>"+
                "<button class='am-btn am-btn-default am-btn-xs am-text-secondary' onclick='readLog(\""+data[i].logFileUri+"\")'><span class='am-icon-pencil-square-o'></span> 查看</button>"+
                "</div></div></td>"+
                "</tr>"
            );
        }
    }
}

$("#logSearch").click(function() {
    if($("#currentTab").val()==1){
        $("#logStartDateTemp").val($("#my-startDate").html());
        $("#logEndDateTemp").val($("#my-endDate").html());
        $("#logSearchContentTemp").val($("#searchContent").val());
        $.ajax({
            type:"POST",
            url:constUrl+"log/search",
            dataType:"json",
            data: {
                startDate: $("#my-startDate").html(),
                endDate: $("#my-endDate").html(),
                content: $("#searchContent").val(),
                onePageCount: "10",
                currentPage: 1,
                operateLog: 1
            },
            success:function(data){
                $("#logIsSearch").val(1);
                $("#operateLog").val(1);
                addPageNum(data.result.pageNum, '1');
                paginationInit('1');
                addBox(data.result.logs, 'logTableList');
            },
            error:function () {
                console.log(pagenumber);
            }
        });
    }
    if($("#currentTab").val()==2){
        $("#runStartDateTemp").val($("#my-startDate").html());
        $("#runEndDateTemp").val($("#my-endDate").html());
        $("#runSearchContentTemp").val($("#searchContent").val());
        $.ajax({
            type:"POST",
            url:constUrl+"log/search",
            dataType:"json",
            data: {
                startDate: $("#my-startDate").html(),
                endDate: $("#my-endDate").html(),
                content: $("#searchContent").val(),
                onePageCount: "10",
                currentPage: 1,
                operateLog: 0
            },
            success:function(data){
                $("#runIsSearch").val(1);
                $("#operateLog").val(0);
                addPageNum(data.result.pageNum, '2');
                paginationInit('2');
                addBox(data.result.logs, 'runTableList');
            },
            error:function () {
                console.log(pagenumber);
            }
        });
    }
});



$('#list-tab').find('a').on('opened.tabs.amui', function(e) {
    $("#currentTab").val($(this).attr('tabNum'));
});

function readLog(id){
    console.log(id);
    layer.open({
        type: 2,
        skin: 'layui-layer-lan',
        title: '日志查看',
        fix: false,
        scrollbar: false,
        shadeClose: true,
        maxmin: true,
        area: ['100%', '100%'],
        content: constUrl+ 'views/log/detail.action?url='+id
    });
}

document.onkeydown=keyDownSearch;

function keyDownSearch(e) {
    // 兼容FF和IE和Opera
    var theEvent = e || window.event;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
        if($("#currentTab").val()==1){
            $("#logStartDateTemp").val($("#my-startDate").html());
            $("#logEndDateTemp").val($("#my-endDate").html());
            $("#logSearchContentTemp").val($("#searchContent").val());
            $.ajax({
                type:"POST",
                url:constUrl+"log/search",
                dataType:"json",
                data: {
                    startDate: $("#my-startDate").html(),
                    endDate: $("#my-endDate").html(),
                    content: $("#searchContent").val(),
                    onePageCount: "10",
                    currentPage: 1
                },
                success:function(data){
                    $("#logIsSearch").val(1);
                    addPageNum(data.result.pageNum, '1');
                    paginationInit('1');
                    addBox(data.result.logs, 'logTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        }
        if($("#currentTab").val()==2){
            $("#runStartDateTemp").val($("#my-startDate").html());
            $("#runEndDateTemp").val($("#my-endDate").html());
            $("#runSearchContentTemp").val($("#searchContent").val());
            $.ajax({
                type:"POST",
                url:constUrl+"log/search",
                dataType:"json",
                data: {
                    startDate: $("#my-startDate").html(),
                    endDate: $("#my-endDate").html(),
                    content: $("#searchContent").val(),
                    onePageCount: "10",
                    currentPage: 1
                },
                success:function(data){
                    $("#runIsSearch").val(1);
                    addPageNum(data.result.pageNum, '2');
                    paginationInit('2');
                    addBox(data.result.logs, 'runTableList');
                },
                error:function () {
                    console.log(pagenumber);
                }
            });
        }
        return false;
    }
    return true;
}